package com.fotkidemo;

import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ProgressBar;
import com.fotkidemo.util.BitmapCache;
import com.fotkidemo.util.DiskCache;
import com.fotkidemo.util.ImageDownloader;

/**
 * Created with IntelliJ IDEA.
 * User: roma
 * Date: 6/28/12
 * Time: 3:15 AM
 * To change this template use File | Settings | File Templates.
 */

/**
 * Отображение фото на весь экран
 */
public class ImageDetailFragment extends Fragment {
    public static final String TAG = "ImageDetailFragment";
    private static final String IMAGE_URL = "image_url";
    public static final String POSITION = "position";
    private int pos;
    private String URL;
    private ImageView imageView;
    private ProgressBar progressBar;

    public static ImageDetailFragment newInstance(int position, String url) {
        final ImageDetailFragment f = new ImageDetailFragment();

        final Bundle args = new Bundle();
        args.putInt(POSITION, position);
        args.putString(IMAGE_URL, url);
        f.setArguments(args);

        return f;
    }

    public ImageDetailFragment() {}

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        pos = getArguments() != null ? getArguments().getInt(POSITION) : -1;
        URL = getArguments() != null ? getArguments().getString(IMAGE_URL) : "";
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        final View v = inflater.inflate(R.layout.image_detail_fragment, container, false);
        imageView = (ImageView) v.findViewById(R.id.imageView);
        progressBar = (ProgressBar) v.findViewById(R.id.progress_Bar);
        progressBar.setVisibility(View.VISIBLE);
        return v;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        if (ImageDetailActivity.class.isInstance(getActivity())) {
            DiskCache diskCache = ((ImageDetailActivity) getActivity()).getDiskCache();
            ImageDownloader imageDownloader = new ImageDownloader(progressBar);
            BitmapCache cache = BitmapCache.getInstance();
            Bitmap bitmap = cache.get(URL);
            if (bitmap != null) {
                if (BuildConfig.DEBUG)
                    Log.d(TAG, "image found in bitmap cache");

                imageView.setImageBitmap(bitmap);
            } else {
                imageDownloader.download(URL, imageView, diskCache);
            }
        }
    }

    public void cancelWork() {
        imageView.setImageDrawable(null);
        imageView = null;
    }
}
